﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using pinduoduo.Util;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
          
            bool newMutexCreated = true;
            using (new Mutex(true, Assembly.GetExecutingAssembly().FullName, out newMutexCreated))
            {

                if (!newMutexCreated)
                {
                    MessageBox.Show("程序已启动！请不要启动多个程序");
                    System.Environment.Exit(0);
                }
                else
                {
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
           
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
#if DEBUG
#else
                   
                    AutoUpdate.GetInstance().Start();
#endif
                    LogHelper.Initialize(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");

                    //处理UI线程异常
                    Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                    //处理非线程异常
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                    LogHelper.Logger.Debug("程序启动");
                    string sqlFilePath = AppDomain.CurrentDomain.BaseDirectory + "Tmp";
                    bool result =  SqlUpdateHelper.SqlUpdate.AutoUpdate(sqlFilePath);
                    if (!result) 
                    {
                        MessageBox.Show("升级数据失败，请退出杀毒软件试试,实在不行请联系客服");
                        return;
                    }
                    MachineCode.GetMachineCode();
                    var settings = new CefSettings
                    {
                        Locale = "zh-CN"
                    };
                    settings.RootCachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\";
                    settings.PersistSessionCookies = true;
                    settings.PersistUserPreferences = true;
                    settings.RemoteDebuggingPort = 22222;
                //    settings.UserAgent = "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19";

                    Cef.Initialize(settings);
                    LogHelper.Logger.Debug("启动程序");
                    Application.Run(new Login());

                }
            }



        }

        /// <summary>
        /// 处理未捕获异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {

            LogHelper.Logger.Debug("-----------------------begin--------------------------");
            LogHelper.Logger.Debug("CurrentDomain_UnhandledException" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            LogHelper.Logger.Debug("IsTerminating : " + e.IsTerminating.ToString());
            LogHelper.Logger.Debug(e.ExceptionObject.ToString());
        }

        /// <summary>
        /// 处理UI主线程异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LogHelper.Logger.Debug("-----------------------begin--------------------------");
            LogHelper.Logger.Debug("Application_ThreadException:" + e.Exception.Message);
            LogHelper.Logger.Debug(e.Exception.StackTrace);
            LogHelper.Logger.Debug("-----------------------end----------------------------");
        }

        private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            CefUtils.KillDriver();
            //var processes =  Process.GetProcessesByName("chromedriver");
            //foreach (var processe in processes)
            //{
            //    try
            //    {
            //        processe.Kill();
            //    }
            //    catch (Exception)
            //    {
            //    }
            //}
        }
      
    }
}
